package com.sunyur.tailor.channel.service.inner.file.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Author: HuBaoding
 * @Description:
 * @Date: Created in 14:12 2021/8/11
 */
@Slf4j
@Service
public class FileDownloadTokenLimiter {

    /**
     * 服务启动后，1分钟即开启任务
     */
    @PostConstruct
    public void initTokenLimiterTask() {
        init();
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(()->addToken(),1,1,TimeUnit.MINUTES);
    }
    // 指定队列最大容量
    private static final int maxSize=10;

    private ArrayBlockingQueue<String> blockingQueue=new ArrayBlockingQueue<>(maxSize);

    /**
     * 初始化令牌操作
     */
    private void init() {
        for (int i = 0; i < maxSize; i++) {
            blockingQueue.add("1");
        }
    }

    /**
     * 获取令牌为空，返回false
     * @return
     */
    public boolean tryAcquire(){
        return blockingQueue.poll() != null;
    }

    private void addToken(){
        log.info("blockingQueue.size: {}", blockingQueue.size());
        if(blockingQueue.size() < maxSize){
            blockingQueue.offer("1");
            log.info("blockingQueue.offer");
        }
    }
}
